﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Assessment.Management.SharedComponent.Params.ManagerParam;
using Assessment.Management.SharedComponent.Constants;
using Assessment.Management.SharedComponent.Entities;
using Assessment.Management.BIZ;
using Assessment.Management.SharedComponent.Params.CommonParam;

namespace Assessment.Management.UI.Assessment
{
    public partial class Default : System.Web.UI.Page
    {
        string classID;
        string subjectID;
        string teacherID;

        protected void Page_Load(object sender, EventArgs e)
        {
            //if (Request.Cookies["password"] == null)
            //{
            //    Response.Redirect("Admin/LoginToAccess.aspx");
            //    return;
            //}
            //string password = Request.Cookies["password"].Value;
            //string subjectid = Request.Cookies["subjectid"].Value;
            //string teacherid = Request.Cookies["teacherid"].Value;
            //string classid = Request.Cookies["classid"].Value;

            string password = "123";
            string subjectid = "2";
            string teacherid = "1";
            string classid = "1";

            //Get pollsetting to check
            PollParam param = new PollParam(FunctionType.GetPollInput);
            Poll poll = new Poll();
            poll.Password = password;
            poll.TeacherID = int.Parse(teacherid);
            poll.ClassID = int.Parse(classid);
            poll.SubjectID = int.Parse(subjectid);
            param.Poll = poll;
            MainController.Provider.Execute(param);

            if (param.Poll == null)
            {
                Response.Redirect("Admin/LoginToAccess.aspx");
                return;
            }
            classID = param.Poll.ClassID.ToString();
            subjectID = param.Poll.SubjectID.ToString();
            teacherID = param.Poll.TeacherID.ToString();
            txtClassName.Text = param.Poll.ClassName;
            txtSubjectName.Text = param.Poll.SubjectName;
            txtTeacherName.Text = param.Poll.TeacherName;
            if (IsPostBack) return;

            //Load group question
            GroupQuestionParam paramGroupQuestion = new GroupQuestionParam(FunctionType.GetListGroupQuestion);
            MainController.Provider.Execute(paramGroupQuestion);
            rptGroupQuestion.DataSource = paramGroupQuestion.listGroupQuestion;
            rptGroupQuestion.DataBind();

        }

        protected void rptGroupQuestion_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            HiddenField hdGroupID = (HiddenField)e.Item.FindControl("hdGroupID");
            Repeater rptQuestionType1 = (Repeater)e.Item.FindControl("rptQuestionType1");
            Repeater rptQuestionType2 = (Repeater)e.Item.FindControl("rptQuestionType2");
            Repeater rptQuestionType3 = (Repeater)e.Item.FindControl("rptQuestionType3");

            GroupQuestionParam paramGroupQuestion = new GroupQuestionParam(FunctionType.GetGroupQuestionByID);
            paramGroupQuestion.GroupQuestion = new GroupQuestion() { ID = int.Parse(hdGroupID.Value) };
            MainController.Provider.Execute(paramGroupQuestion);

            QuestionParam paramQuestion = new QuestionParam(FunctionType.GetListQuestionByGroupID);
            paramQuestion.Question = new Question() { GroupID = int.Parse(hdGroupID.Value) };
            MainController.Provider.Execute(paramQuestion);

            switch (paramGroupQuestion.GroupQuestion.DisplayStyle)
            {
                case SMX.am_IsQuestionSelect:
                    rptQuestionType1.DataSource = paramQuestion.listQuestion;
                    rptQuestionType1.DataBind();
                    break;
                case SMX.am_IsQuestionSelectABCDE:
                    Label label = (Label)e.Item.FindControl("lblTableHeader");
                    label.Text = "<center><b>Hãy đọc kĩ các câu sau và chọn phương án trả lời phù hợp với ý kiến của riêng anh (chị).</br>" +
                "A: Hoàn toàn đồng ý&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;B: Đồng ý&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;C: " +
                            "Tương đối đồng ý&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;D: Không đồng ý&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;E:" +
                            " Không có ý kiến</b></center>" +
                        "<tr style=\"text-align: center; font-weight: bold; background-color: #E3EDFA; height: 30px;\">" +
                                        "<td class=\"form\">STT</td>" +
                                        "<td class=\"form\">Hoạt động giảng dạy</td>" +
                                        "<td class=\"form\" width=\"40px\">A</td>" +
                                        "<td class=\"form\" width=\"40px\">B</td>" +
                                        "<td class=\"form\" width=\"40px\">C</td>" +
                                        "<td class=\"form\" width=\"40px\">D</td>" +
                                        "<td class=\"form\" width=\"40px\">E</td></tr>";

                    //STT = (int)db.Questions.Where(q => q.GroupID == 1).Count() + 1;

                    rptQuestionType2.DataSource = paramQuestion.listQuestion;
                    rptQuestionType2.DataBind();
                    break;
                case SMX.am_IsQuestionHaveTextboxAndSelect:
                    Label label2 = (Label)e.Item.FindControl("lblTableHeader");
                    label2.Text = "";
                    rptQuestionType3.DataSource = paramQuestion.listQuestion;
                    rptQuestionType3.DataBind();
                    break;
                default:
                    throw new NotSupportedException();
            }
        }

        protected void rptQuestionType1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            HiddenField hdQuestionID = (HiddenField)e.Item.FindControl("hdQuestionID");
            RadioButtonList rdoAnswer = (RadioButtonList)e.Item.FindControl("rdoAnswer");

            OptionParam paramOption = new OptionParam(FunctionType.GetListOptionByQuestionID);
            paramOption.Option = new Option() { QuestionID = int.Parse(hdQuestionID.Value) };
            MainController.Provider.Execute(paramOption);
            rdoAnswer.DataSource = paramOption.listOption;
            rdoAnswer.DataBind();
        }
        int STT = 1;
        protected void rptQuestionType2_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            HiddenField hdQuestionID2 = (HiddenField)e.Item.FindControl("hdQuestionID2");
            RadioButtonList rdoAnswer2 = (RadioButtonList)e.Item.FindControl("rdoAnswer2");
            Repeater rptAnswer2 = (Repeater)e.Item.FindControl("rptAnswer2");

            OptionParam paramOption = new OptionParam(FunctionType.GetListOptionByQuestionID);
            paramOption.Option = new Option() { QuestionID = int.Parse(hdQuestionID2.Value) };
            MainController.Provider.Execute(paramOption);
            rdoAnswer2.DataSource = paramOption.listOption;
            rdoAnswer2.DataBind();
            
            Label lblSTT = (Label)e.Item.FindControl("lblSTT2");
            lblSTT.Text = (STT++).ToString();
        }

        protected void rptQuestionType3_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            HiddenField hdQuestionID3 = (HiddenField)e.Item.FindControl("hdQuestionID3");
            RadioButtonList rdoAnswer3 = (RadioButtonList)e.Item.FindControl("rdoAnswer3");
            TextBox txtAnswer = (TextBox)e.Item.FindControl("txtAnswer");

            QuestionParam paramQuestion = new QuestionParam(FunctionType.GetListQuestionByID);
            paramQuestion.Question = new Question() { ID = int.Parse(hdQuestionID3.Value) };
            MainController.Provider.Execute(paramQuestion);

            if (paramQuestion.Question.Type == 1)
            {
                OptionParam paramOption = new OptionParam(FunctionType.GetListOptionByQuestionID);
                paramOption.Option = new Option() { QuestionID = int.Parse(hdQuestionID3.Value) };
                MainController.Provider.Execute(paramOption);

                rdoAnswer3.DataSource = paramOption.listOption;
                rdoAnswer3.DataBind();
                txtAnswer.Visible = false;
            }
            else
            {
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem groupitem in rptGroupQuestion.Items)
            {
                Repeater rptQuestionType1 = (Repeater)groupitem.FindControl("rptQuestionType1");
                Repeater rptQuestionType2 = (Repeater)groupitem.FindControl("rptQuestionType2");
                Repeater rptQuestionType3 = (Repeater)groupitem.FindControl("rptQuestionType3");

                foreach (RepeaterItem questionitem in rptQuestionType1.Items)
                {
                    HiddenField hdQuestionID = (HiddenField)questionitem.FindControl("hdQuestionID");
                    RadioButtonList rdoAnswer = (RadioButtonList)questionitem.FindControl("rdoAnswer");
                    Label lblCheck1 = (Label)questionitem.FindControl("lblCheck1");
                    //string qid = hdQuestionID.Value;
                    if (rdoAnswer == null) continue;
                    string answer = rdoAnswer.SelectedValue;
                    if (rdoAnswer.SelectedIndex < 0) continue;

                    // tra loi cau hoi qid, voi cau tra loi thu answer
                    OptionHit opthit = GetOptionHitBySubjectIDAndClassID(answer, subjectID, classID);

                    if (opthit == null)
                    {
                        //Save new option hit
                        SaveNewOptionHit(answer, subjectID, classID);
                    }
                    else
                    {
                        //Update  Sum into hit count
                        int hit = opthit.HitCount + 1;
                        UpdateHitCount(answer, subjectID, classID, hit);
                    }
                }
                foreach (RepeaterItem questionitem2 in rptQuestionType2.Items)
                {
                    HiddenField hdQuestionID2 = (HiddenField)questionitem2.FindControl("hdQuestionID2");
                    RadioButtonList rdoAnswer2 = (RadioButtonList)questionitem2.FindControl("rdoAnswer2");
                    //string qid = hdQuestionID.Value;
                    if (rdoAnswer2 == null) continue;
                    string answer2 = rdoAnswer2.SelectedValue;
                    if (rdoAnswer2.SelectedIndex < 0) continue;

                    // tra loi cau hoi qid, voi cau tra loi thu answer
                    OptionHit opthit2 = GetOptionHitBySubjectIDAndClassID(answer2, subjectID, classID);
                    if (opthit2 == null)
                    {
                        //Save new option hit
                        SaveNewOptionHit(answer2, subjectID, classID);
                    }
                    else
                    {
                        //Update  Sum into hit count
                        int hit = opthit2.HitCount + 1;
                        UpdateHitCount(answer2, subjectID, classID, hit);
                    }
                }

                foreach (RepeaterItem questionitem3 in rptQuestionType3.Items)
                {
                    HiddenField hdQuestionID3 = (HiddenField)questionitem3.FindControl("hdQuestionID3");
                    RadioButtonList rdoAnswer3 = (RadioButtonList)questionitem3.FindControl("rdoAnswer3");

                    QuestionParam paramQuestion = new QuestionParam(FunctionType.GetListQuestionByID);
                    paramQuestion.Question = new Question() { ID = int.Parse(hdQuestionID3.Value) };
                    MainController.Provider.Execute(paramQuestion);

                    if (paramQuestion.Question.Type == 1)
                    {

                        //string qid = hdQuestionID.Value;
                        if (rdoAnswer3 == null) continue;
                        string answer3 = rdoAnswer3.SelectedValue;
                        if (rdoAnswer3.SelectedIndex < 0) continue;
                        // tra loi cau hoi qid, voi cau tra loi thu answer
                        OptionHit opthit3 = GetOptionHitBySubjectIDAndClassID(answer3, subjectID, classID);
                        if (opthit3 == null)
                        {
                            //Save new option hit
                            SaveNewOptionHit(answer3, subjectID, classID);
                        }
                        else
                        {
                            //Update  Sum into hit count
                            int hit = opthit3.HitCount + 1;
                            UpdateHitCount(answer3, subjectID, classID, hit);
                        }
                    }
                    else
                    {
                        TextBox txtAnswer = (TextBox)questionitem3.FindControl("txtAnswer");
                        if (txtAnswer != null)
                        {
                            //Update Question Student
                            QuestionStudentParam paramQuestionStudent = new QuestionStudentParam(FunctionType.InsertAnswerOfQuestion);
                            QuestionStudent qs = new QuestionStudent();
                            qs.QuestionID = int.Parse(hdQuestionID3.Value);
                            qs.SubjectID = int.Parse(subjectID);
                            qs.ClassID = int.Parse(classID);
                            qs.Answer = txtAnswer.Text;
                            paramQuestionStudent.QuestionStudent=qs;
                            MainController.Provider.Execute(paramQuestionStudent);
                        }
                    }
                }
            }
            //TODO: 08/05/2014 Save Teacher Class. Kiểm tra lại có cần update tại đây hay update tại config

            //Teacher_Class teacherclass = db.Teacher_Classes.SingleOrDefault(tcs => tcs.TeacherID.ToString() == teacherID
            //    && tcs.ClassID.ToString() == classID && tcs.SubjectID.ToString() == subjectID);
            //if (teacherclass == null)
            //{
            //    Teacher_Class tc = new Teacher_Class();
            //    tc.TeacherID = int.Parse(teacherID);
            //    tc.ClassID = int.Parse(classID);
            //    tc.SubjectID = int.Parse(subjectID);
            //    db.Teacher_Classes.InsertOnSubmit(tc);
            //}
            //else
            //{
            //    Teacher_Class tc = new Teacher_Class();
            //    tc.TeacherID = int.Parse(teacherID);
            //    tc.ClassID = int.Parse(classID);
            //    tc.SubjectID = int.Parse(subjectID);

            //}
            //db.SubmitChanges();
            Response.Redirect("ThankYou.aspx");
        }

        private OptionHit GetOptionHitBySubjectIDAndClassID(string optID, string sID, string cID)
        {
            OptionHitParam paramOptionHit = new OptionHitParam(FunctionType.GetOptionHitBySubjectIDAndClassID);
            paramOptionHit.OptionHit = new OptionHit() { OptionID = int.Parse(optID), ClassID = int.Parse(cID), SubjectID = int.Parse(sID) };
            MainController.Provider.Execute(paramOptionHit);
            return paramOptionHit.OptionHit;
        }

        private void UpdateHitCount(string optID, string sID, string cID, int hitcount)
        {
            OptionHitParam paramOptionHit = new OptionHitParam(FunctionType.UpdateOptionHitCount);
            OptionHit opthit = new OptionHit();
            opthit.OptionID = int.Parse(optID);
            opthit.SubjectID = int.Parse(sID);
            opthit.ClassID = int.Parse(cID);
            opthit.HitCount = hitcount;
            paramOptionHit.OptionHit = opthit;
            MainController.Provider.Execute(paramOptionHit);
        }

        private void SaveNewOptionHit(string optID, string sID, string cID)
        {
            OptionHitParam paramOptionHit = new OptionHitParam(FunctionType.InsertNewOptionHit);
            OptionHit newhit = new OptionHit();
            newhit.OptionID = int.Parse(optID);
            newhit.SubjectID = int.Parse(sID);
            newhit.ClassID = int.Parse(cID);
            newhit.HitCount = 0;
            newhit.HitCount++;
            paramOptionHit.OptionHit = newhit;
            MainController.Provider.Execute(paramOptionHit);
        }
    }
}